package utils

import (
	"service/constant"
	"service/modules"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

type UserClaims struct {
	UserId     int64
	UserName   string
	UserNick   string
	Phone      string
	Email      string
	LoginIp    string
	Department string
	jwt.RegisteredClaims
}

func GenerateToken(user *modules.Users) (string, error) {
	// 过期时间
	exTime := time.Now().Add(24 * time.Hour)
	claims := &UserClaims{
		UserId:     user.Id,
		UserName:   user.UserName,
		UserNick:   user.NickName,
		Phone:      user.Phone,
		Email:      user.Email,
		LoginIp:    user.LoginIp,
		Department: user.Department,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(exTime),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			Issuer:    "lysimportant@outlook.com",
			Subject:   "weWin",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenStr, err := token.SignedString([]byte(constant.JwtKey))
	return tokenStr, err
}

func ParseToken(tokenStr string) (*jwt.Token, *UserClaims, error) {
	claims := new(UserClaims)
	token, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (i interface{}, err error) {
		return []byte(constant.JwtKey), nil
	})
	return token, claims, err
}
